<template>
    <div class="antd_layout">
        <div class="layout_sider">
            <a-row>
                <a-col class="customCol_6" :span="6"> 配置模板： </a-col>
                <a-col :span="18">
                    <a-tree-select
                        v-model:value="currentVal"
                        show-search
                        style="width: 100%"
                        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                        placeholder="请选择"
                        allow-clear
                        tree-default-expand-all
                        :tree-data="treeData"
                    >
                    </a-tree-select>
                </a-col>
            </a-row>
            <div class="marginTop20">
                <EditeTable :dataSource="dataSource" @changeDataSource="changeDataSource"></EditeTable>
            </div>
            <div class="marginTop20">
                <a-row>
                    <a-col class="customCol_8" :span="6"> 数据起始行： </a-col>
                    <a-col :span="6">
                        <a-input v-model:value="tableStartLine" placeholder="请输入" @change="inputChangeFn" />
                    </a-col>
                </a-row>
            </div>
            <div class="marginTop20">
                <a-checkbox-group v-model:value="sheetPropsConf" style="width: 100%" @change="checkBoxGroupChangeFn">
                    <a-row>
                        <a-col :span="24">
                            <a-checkbox value="sheetsShare">多Sheet页共享配置</a-checkbox>
                        </a-col>
                        <a-col :span="24">
                            <a-checkbox value="autoAnalysis">自动分析数据属性</a-checkbox>
                        </a-col>
                    </a-row>
                </a-checkbox-group>
            </div>
            <div class="marginTop20">
                <DescCard :descInfo="descInfo" />
            </div>
            <div class="marginTop20 opetors">
                <a-button type="primary" @click="close">取消</a-button>
                <a-button type="primary" @click="saveTpls">保存模版</a-button>
                <a-button type="primary" @click="importFun">导入</a-button>
            </div>
        </div>
        <div class="layout_content">
            <div class="search_form">
                <SearchForm ref="temSearchForm" :columnsNum="3" :isShowSearchBtns="true" :formdata="formdata" :formItems="formItems">
                    <!-- <template #customFormBtns>
                        <a-button type="primary" html-type="submit">Submit</a-button>
                    </template> -->
                </SearchForm>
            </div>
            <div class="lucky_table marginTop20">
                <div id="luckysheet_config" style="margin: 0px; padding: 0px"></div>
            </div>
        </div>
    </div>
</template>

<script>
import lodash from 'lodash';

import EditeTable from './Component/editeTable.vue';
import DescCard from '@/components/CustomCard/DescCard.vue';
import SearchForm from '@/components/CustomSearch/searchForm.vue';

import { useTplInfoStore } from '@/store';

import { addTemplate, importData } from '@/request/api/dataSourceAPI';

import { message } from 'ant-design-vue';

export default {
    components: {
        DescCard,
        SearchForm,
        EditeTable,
    },
    props: {
        drawerFile: {
            type: Object,
            default: () => ({}),
        },
        allRowData: {
            type: Array,
            default: () => [],
        },
    },
    data() {
        return {
            currentVal: 'parent 1-0',
            treeData: [
                {
                    title: 'parent 1',
                    value: 'parent 1',
                    children: [
                        {
                            title: 'parent 1-0',
                            value: 'parent 1-0',
                            children: [
                                {
                                    title: 'my leaf',
                                    value: 'leaf1',
                                },
                                {
                                    title: 'your leaf',
                                    value: 'leaf2',
                                },
                            ],
                        },
                        {
                            title: 'parent 1-1',
                            value: 'parent 1-1',
                        },
                    ],
                },
            ],
            tableStartLine: 1,
            sheetPropsConf: [],
            // 属性面板
            descInfo: [
                {
                    title: '属性',
                    items: [
                        {
                            name: '区划：',
                            key: 'division',
                            value: '304822',
                        },
                        {
                            name: '年度：',
                            key: 'years',
                            value: '2022',
                        },
                        {
                            name: '报表日期(起)：',
                            key: 'start_time',
                            value: '2022-09-04',
                        },
                        {
                            name: '报表日期(止)：',
                            key: 'end_time',
                            value: '2022-09-04',
                        },
                        {
                            name: '金额单位：',
                            key: 'price',
                            value: '元',
                        },
                    ],
                },
            ],
            // 查询表单
            formdata: {},
            formItems: [],
            // 当前sheet的单元格配置，可编辑表格部分
            dataSource: [],
            // 当前sheet页
            curActive: 0,
        };
    },
    mounted() {
        this.initConfigTable();
        this.getTplInfoStoreToData(0);
    },
    methods: {
        // 根据dataSource当中的列类型动态创建查询表单
        getformItems() {
            this.formItems = this.dataSource
                .filter((item) => item.columnType === 2)
                .map(({ columnCode, columnName, columnType }) => ({
                    name: columnCode,
                    label: columnName,
                    rules: [],
                    itemInfo: {
                        type: 'Input',
                        events: {
                            // 支持组件的事件
                            // change(value){
                            //   console.log(value)
                            // },
                            input(value) {
                                console.log(value);
                            },
                        },
                    },
                }));
        },

        // 取出store中由新增模板时保存的后端分析出的模板信息
        getTplInfoStoreToData(activeIndex = 0) {
            this.curActive = activeIndex;
            const TplInfoStore = useTplInfoStore();
            console.log(TplInfoStore, 'tpl analysis data');
            // 当前sheet的单元格配置，可编辑表格部分
            this.dataSource = TplInfoStore.hotData[activeIndex]['template']['importColumns'];
            // 当前sheet的数据起始行
            this.tableStartLine = TplInfoStore.hotData[activeIndex]['template']['startLine'];
            // checkbox部分
            const autoAnalysis = TplInfoStore.hotData[activeIndex]['template']['autoAnalysis'];
            this.sheetPropsConf = ['', autoAnalysis ? 'autoAnalysis' : ''];
            // 根据dataSource当中的列类型动态创建查询表单
            this.getformItems();
            // 属性面板部分
            const descInfoItems = TplInfoStore.hotData[activeIndex]['properties'];
            this.descInfo = [
                {
                    title: '属性',
                    items: descInfoItems.map(({ id, name, value, typeCode }) => ({
                        id,
                        name,
                        key: typeCode,
                        value,
                    })),
                },
            ];
        },

        // 编辑表格原数据
        changeDataSource(key, editableData) {
            Object.assign(this.dataSource.filter((item, index) => key === index)[0], editableData[key]);
            this.getformItems();
        },

        // 初始化抽屉页luckysheet表格
        initConfigTable() {
            luckysheet.destroy();
            let that = this;
            var options = {
                container: 'luckysheet_config', //luckysheet为容器id
                lang: 'zh',
                allowEdit: false, // 是否允许前台编辑
                showtoolbar: false, // 是否显示工具栏
                showinfobar: false, // 是否显示顶部信息栏
                sheetFormulaBar: false, // 是否显示公式栏
                showsheetbarConfig: {
                    add: false, //新增sheet  
                    menu: false, //sheet管理菜单
                    sheet: true //sheet页显示
                },
                sheetRightClickConfig: {
                    delete: false, // 删除
                    copy: false, // 复制
                    rename: false, //重命名
                    color: false, //更改颜色
                    hide: false, //隐藏，取消隐藏
                    move: false, //向左移，向右移
                },
                hook: {
                    rangeSelect: function (sheet, range) {
                        // console.log(sheet)
                        // console.log(range)
                    },
                    sheetActivate: function (index, isPivotInitial, isNewSheet) {
                        // luckysheet.setSheetActive(1) // 手动激活指定sheet页
                        // luckysheet.getSheet(index).name
                        console.info(index, isPivotInitial, isNewSheet);
                        that.getTplInfoStoreToData(index - 1);
                    },
                },
                data: lodash.isEmpty(that.drawerFile)
                    ? [
                          {
                              name: 'Cell', //工作表名称
                              color: '', //工作表颜色
                              index: 0, //工作表索引
                              status: 1, //激活状态
                              order: 0, //工作表的下标
                              hide: 0, //是否隐藏
                              row: 36, //行数
                              column: 18, //列数
                              defaultRowHeight: 19, //自定义行高
                              defaultColWidth: 73, //自定义列宽
                              celldata: [
                                  {
                                      r: 0,
                                      c: 0,
                                      v: {
                                          ct: { fa: 'General', t: 'g' },
                                          m: 'value1',
                                          v: 'value1',
                                      },
                                  },
                                  {
                                      r: 0,
                                      c: 1,
                                      v: {
                                          ct: { fa: 'General', t: 'g' },
                                          m: 'value2',
                                          v: 'value2',
                                      },
                                  },
                              ], //初始化使用的单元格数据
                              config: {
                                  merge: {}, //合并单元格
                                  rowlen: {}, //表格行高
                                  columnlen: {}, //表格列宽
                                  rowhidden: {}, //隐藏行
                                  colhidden: {}, //隐藏列
                                  borderInfo: {}, //边框
                                  authority: {}, //工作表保护
                              },
                              scrollLeft: 0, //左右滚动条位置
                              scrollTop: 0, //上下滚动条位置
                              luckysheet_select_save: [], //选中的区域
                              calcChain: [], //公式链
                              isPivotTable: false, //是否数据透视表
                              pivotTable: {}, //数据透视表设置
                              filter_select: {}, //筛选范围
                              filter: null, //筛选配置
                              luckysheet_alternateformat_save: [], //交替颜色
                              luckysheet_alternateformat_save_modelCustom: [], //自定义交替颜色
                              luckysheet_conditionformat_save: {}, //条件格式
                              frozen: {}, //冻结行列配置
                              chart: [], //图表配置
                              zoomRatio: 1, // 缩放比例
                              image: [], //图片
                              showGridLines: 1, //是否显示网格线
                              dataVerification: {}, //数据验证配置
                          },
                          {
                              name: 'Sheet2',
                              color: '',
                              index: 1,
                              status: 0,
                              order: 1,
                              celldata: [],
                              config: {},
                          },
                          {
                              name: 'Sheet3',
                              color: '',
                              index: 2,
                              status: 0,
                              order: 2,
                              celldata: [],
                              config: {},
                          },
                      ]
                    : that.drawerFile,
            };
            setTimeout(() => {
                luckysheet.create(options);
            }, 500);
        },

        // 数据起始行输入框change事件
        inputChangeFn(e) {
            const TplInfoStore = useTplInfoStore();
            TplInfoStore.changeCurStartLine(this.curActive, Number(e.target.value));
        },

        // 起始行、自动分析复选框change事件
        checkBoxGroupChangeFn(e) {
            const TplInfoStore = useTplInfoStore();
            TplInfoStore.changeCheckbox(this.curActive, this.sheetPropsConf);
        },

        // 保存模板按钮点击事件
        saveTpls() {
            const TplInfoStore = useTplInfoStore();
            const tplData = TplInfoStore.hotData.map((item) => item.template);
            // 保存一个excel文件当中全部sheet页的模板
            addTemplate(tplData).then((res) => {
                if (res.state == '200') {
                    message.success(res.msg || '模板保存成功！');
                    // this.changeIsvisible()
                } else {
                    message.error(res.msg || '模板保存失败！');
                }
            });
        },

        // 取消按钮点击事件
        close() {
            debugger
            this.$emit('close')
        },

        // 导入按钮点击事件
        importFun() {
            let data = {
                fullname: '',
                name: this.allRowData[0]['table']['fileName'],
                sheets: this.allRowData,
            };
            // 导入excel文件保存落库
            importData(data).then((res) => {
                if (res.state == '200') {
                    this.$emit('close')
                    return message.success(res.msg || '导入成功！');
                } else {
                    // this.$emit('close')
                    return message.error(res.msg || '导入失败！');
                }
            });
        },
    },
};
</script>

<style lang="less" scoped>
.antd_layout {
    display: flex;
    justify-content: space-between;
    height: 100%;
    width: 100%;
}
.layout_sider {
    display: inline-block;
    padding: 20px;
    height: 100%;
    width: 30%;
    border: 2px solid #f6f6f6;
    overflow-y: auto;
}
.layout_content {
    // display: inline-block;
    // flex: 1;
    padding: 20px;
    // height: 100%;
    // border: 2px solid #f6f6f6;
    .search_form {
        min-height: 112px;
        overflow-x: hidden;
        overflow-y: auto;
    }
    .lucky_table {
        height: calc(100% - 112px);
        #luckysheet_config {
            height: 100%;
        }
    }
}

.marginTop20 {
    margin-top: 20px;
}

.customCol_6,
.customCol_8 {
    display: flex;
    align-items: center;
    word-break: keep-all;
}

.opetors {
    display: flex;
    justify-content: space-between;
}
</style>
